(function(){
	var serviceManager = require('../ServiceManager.js');
	
	var onRequest = function(req, res){
		var method = req.params.method;
		var serviceName = req.params.service;
		//console.log(_('Invoker - ${service} ${method}',req.params));
		var service = serviceManager.get(serviceName);
		
		if( service && (!method || method === '_describe')){
			var results = {result:serviceManager._describe(serviceName)};
			res.end(JSON.stringify(results));
		}else if(service && service[method]){
			console.log(req.rawBody);
			var args = req.rawBody ? req.body : [];
			var hasCallback = false;
			iterate(args, function(item, index){
				if( item === '__function'){
					args[index] = function(){
						var _args = [];
						iterate(arguments, function(value, index){
							if( value && value.__alternate )
								_args.push({
									__alternate:value.__alternate
									,__serviceName:value.__alternate
								});
							else
								_args.push(value);
						});
						var data = JSON.stringify({args:_args, index:index});
						res.setHeader('content-type', 'application/json');
						res.setHeader('content-length', data.length);
						res.statusCode = 200;
						res.end(data);
					};
					hasCallback = true;
				}
			});
			//console.log("Args: "+args);
			var result = service[method].apply(service, args);
			if( !hasCallback ){
				var complete = function(){
					var data = JSON.stringify({result:result});
					res.setHeader('content-type', 'application/json');
					res.setHeader('content-length', data.length);
					res.statusCode = 200;
					res.end(data);
				}
				if(result && result.on){
					result.on('ready', complete)
				}else{
					complete();
				}
			}
		}else{
			res.end(_('{error: "Service ${service} not found."}', req.params));
		}
	};
	
	exports.register = function(expressApp){
		expressApp.all('/invoker/:service/:method?', onRequest);
	};
	
})()
